<?php

namespace fakis\config\adapters;

use Yii;
use yii\base\Component;
use yii\helpers\FileHelper;
use yii\helpers\Json;

/**
 * 文件适配器
 *
 * @author Fakis <fakis738@qq.com>
 */
class FileAdapter extends Component implements AdapterInterface
{
    /**
     * 文件路径
     * @var string
     */
    public $filepath = '@runtime/config';

    /**
     * @inheritDoc
     */
    public function init()
    {
        parent::init();

        FileHelper::createDirectory(Yii::getAlias($this->filepath));
    }

    /**
     * 取得文件名
     * @param string $symbol
     * @return string
     */
    public function getFileName($symbol): string
    {
        return Yii::getAlias($this->filepath) . "/{$symbol}.json";
    }

    /**
     * 查询数据
     * @param string $symbol
     * @return array|null
     */
    public function query(string $symbol): ?array
    {
        $result = null;
        $filename = $this->getFileName($symbol);
        if (file_exists($filename) && is_file($filename)) {
            $result = Json::decode(file_get_contents($filename));
        }

        return $result;
    }

    /**
     * 保存配置数据
     * @param string $symbol
     * @param array $attributes
     * @return bool
     */
    public function store(string $symbol, array $attributes): bool
    {
        return (bool)file_put_contents($this->getFileName($symbol), Json::encode($attributes));
    }

    /**
     * 清空配置数据
     * @param string $symbol
     * @return bool
     */
    public function clear(string $symbol): bool
    {
        return (bool)FileHelper::unlink($this->getFileName($symbol));
    }
}